package com.ruoyi.web.task;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.DtoUser;
import com.ruoyi.system.domain.dto.DtoVehicle;
import com.ruoyi.system.service.*;
import com.ruoyi.web.controller.websocket.WebSocketUsers;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 违章定时任务
 *
 * @author lxy
 * @date 2024-04-26
 */
@Component
@EnableScheduling
public class IllegalTask {

    private static final Logger log = LoggerFactory.getLogger(IllegalTask.class);
    private static final String URI = "http://ps.jhm.com.cn:8890/prod-api";

    @Autowired
    private ITbVisitorVehicleService vehicleService;
    @Autowired
    private ITbVehicleIllegalService illegalService;
    @Autowired
    private IOaService oaService;
    @Autowired
    private ITbVisitorUserService tbVisitorUserService;
    @Autowired
    private ITbQrService tbQrService;
    @Autowired
    private ITbScreenService tbScreenService;

    /**
     * 查询当天违章记录
     */
    @Scheduled(cron = "0 0/2 * * * ?")
    public void getIllegalRecord() throws Exception {
        String today = LocalDate.now().toString();
        // 查询当天到访车辆
        DtoVehicle dto = new DtoVehicle();
        dto.setStatus("4");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        dto.setInTimeFrom(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, calendar.getTime()));

        calendar.set(Calendar.HOUR_OF_DAY, 23);
        dto.setInTimeTo(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, calendar.getTime()));
        List<TbVisitorVehicle> vehicleList = vehicleService.selectTbVisitorVehicleList(dto);
        if (CollectionUtils.isNotEmpty(vehicleList)) {
            // 查询当天违章审批
            TbVehicleIllegal query = new TbVehicleIllegal();
            query.setOverspeedDate(today);
            List<TbVehicleIllegal> illegalList = illegalService.selectTbVehicleIllegalList(query);
            List<String> imgs = illegalList.stream().map(TbVehicleIllegal :: getOverspeedImg).collect(Collectors.toList());
            log.info("查询 {} 车辆违章记录", today);
//            File sharedFolder = new File("\\\\10.200.32.3\\1.公司办公室\\share\\超速\\" + today);
            File sharedFolder = new File("D:\\ruoyi\\超速\\share\\超速\\" + today);
            if (sharedFolder.exists() && sharedFolder.isDirectory()) {
                File[] files = sharedFolder.listFiles();
                if (files != null) {
                    for (File file: files) {
                        // 未处理过的超速照片
                        if (file.isFile() && !file.getName().contains("plat") && !imgs.contains(file.getName())) {
                            String fileName = file.getName();
                            log.info("违章车辆 {}", fileName);
                            String[] infos = fileName.substring(0, fileName.lastIndexOf(".")).split("-");
                            Date overspeedDate = DateUtils.parseDate(infos[1].substring(0, 14), "yyyyMMddHHmmss");
                            String speed = infos[3].replace("车辆速度", "");
                            // 上传文件路径
                            String filePath = RuoYiConfig.getUploadPath();
                            // 上传并返回新文件名称
                            MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), null, new FileInputStream(file));
                            String url = URI + FileUploadUtils.upload(filePath, multipartFile);
                            for (TbVisitorVehicle vehicle: vehicleList) {
                                if (infos[0].indexOf(vehicle.getCard())>=0 && overspeedDate.compareTo(vehicle.getInTime()) > 0) {
                                    // 创建审批流程
                                    TbVehicleIllegal illegal = new TbVehicleIllegal();
                                    illegal.setVisitorVehicleId(vehicle.getId());
                                    illegal.setLicenseNo(vehicle.getCard());
                                    illegal.setCarOwner(vehicle.getUserName());
                                    illegal.setOverspeedImg(fileName);
                                    illegal.setOverspeedImgUrl(url);
                                    illegal.setSpeed(speed);
                                    illegal.setOverspeedDate(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", overspeedDate));
                                    illegal.setInterviewedNo(vehicle.getInterviewedNo());
                                    illegal.setInterviewedName(vehicle.getInterviewedName());
                                    String result = oaService.createVehicleIllegalWorkflow(illegal);
                                    // 解析返回结果
                                    JSONObject json = JSONObject.parseObject(result);
                                    if ("100".equals(json.getString("code"))) {
                                        JSONObject data = json.getJSONObject("data");
                                        illegal.setRequestId(data.getString("requestid"));
                                        illegalService.insertTbVehicleIllegal(illegal);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }


    /**
     * 夜间23：50将今日车辆预约、以及过期的访客预约数据全部清空
     */
    @Scheduled(cron = "0 50 23 * * ? ")
    public void delTodayVehicleRecords() {

        LocalDateTime ldt = LocalDateTime.now();
        LocalDateTime threeDaysAgo = ldt.minusDays(2);
        LocalDateTime todayZero = LocalDateTime.of(threeDaysAgo.getYear(), threeDaysAgo.getMonthValue(), threeDaysAgo.getDayOfMonth(), 0, 0, 0);
        LocalDateTime todayLasr = LocalDateTime.of(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(), 23, 59, 59);

        Date dateFrom = Date.from(todayZero.atZone(ZoneId.systemDefault()).toInstant());
        Date dateTo = Date.from(todayLasr.atZone(ZoneId.systemDefault()).toInstant());


        DtoVehicle tbVisitorVehicle = new DtoVehicle();
//        tbVisitorVehicle.setInTimeFrom(dateFrom);
        tbVisitorVehicle.setOutTimeTo(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, dateTo));
        tbVisitorVehicle.setDelFlag("0");

        List<TbVisitorVehicle> rltList = vehicleService.selectTbVisitorVehicleList(tbVisitorVehicle);

        if (rltList != null && rltList.size() > 0) {
            for (TbVisitorVehicle item : rltList) {

                TbVisitorVehicle upd = new TbVisitorVehicle();
                upd.setId(item.getId());
                upd.setUpdateTime(DateUtils.getNowDate());
                upd.setDelFlag("2");
                upd.setStatus("5");
                vehicleService.updateTbVisitorVehicle(upd);
            }
        }

        DtoUser userDto = new DtoUser();
        userDto.setOutTimeTo(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, dateTo));
        userDto.setDelFlag("0");

        List<TbVisitorUser> userList = tbVisitorUserService.selectTbVisitorUserList(userDto);
        if (userList != null && userList.size() > 0) {
            for (TbVisitorUser item : userList) {
                if ("1".equals(item.getIsqr())) {
                    // 二维码未回收的场合，先回收二维码
                    TbQr search = new TbQr();
                    search.setCode(item.getQr());
                    List<TbQr> qrs = tbQrService.selectTbQrList(search);
                    if (qrs != null && qrs.size() > 0) {
                        for (TbQr qitem : qrs) {
                            qitem.setStatus("0");
                            qitem.setUpdateTime(DateUtils.getNowDate());
                            tbQrService.updateTbQr(qitem);
                        }
                    }
                }

                TbVisitorUser upd = new TbVisitorUser();
                upd.setId(item.getId());
                upd.setUpdateTime(DateUtils.getNowDate());
                upd.setDelFlag("2");
                upd.setIsqr("0");
                upd.setStatus("5");
                tbVisitorUserService.updateTbVisitorUser(upd);
            }
        }

        try {

            String uploadPath = RuoYiConfig.getUploadPath() + "/sound/";

            Path dir = Paths.get(uploadPath);
            // 遍历文件夹中的所有文件和子文件夹
            for (Path file : Files.walk(dir).collect(Collectors.toList())) {
                // 删除文件
                if (Files.isRegularFile(file)) {
                    Files.delete(file);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 夜间23：50将今日车辆预约、以及过期的访客预约数据全部清空
     */
    @Scheduled(cron = "0 5 0 * * ? ")
    public void refreshScreen() {

        TbScreen tbScreen = tbScreenService.selectTbScreenById(100L);
        tbScreen.setGoods("0");

        LocalDateTime ldt = LocalDateTime.now();
        LocalDateTime todayZero = LocalDateTime.of(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(), 0, 0, 0);
        LocalDateTime todayLasr = LocalDateTime.of(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(), 23, 59, 59);

        Date dateFrom = Date.from(todayZero.atZone(ZoneId.systemDefault()).toInstant());
        Date dateTo = Date.from(todayLasr.atZone(ZoneId.systemDefault()).toInstant());


        DtoUser tbVisitorUser = new DtoUser();
        tbVisitorUser.setInTimeFrom(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, dateFrom));
        tbVisitorUser.setOutTimeTo(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, dateTo));

        // 访客列表
        List<TbVisitorUser> uList = tbVisitorUserService.selectTbVisitorUserList(tbVisitorUser);
        int userSu = 0;
        if (uList != null && uList.size() > 0) {
            userSu = uList.size();
        }

        DtoVehicle tbVisitorVehicle = new DtoVehicle();
        tbVisitorVehicle.setInTimeFrom(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, dateFrom));
        tbVisitorVehicle.setOutTimeTo(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, dateTo));
        List<TbVisitorVehicle> vlist = vehicleService.selectTbVisitorVehicleList(tbVisitorVehicle);
        int vSu = 0;
        if (vlist != null && vlist.size() > 0) {
            vSu = vlist.size();
        }

        tbScreen.setBooking(String.valueOf(userSu));
        tbScreen.setBookingv(String.valueOf(vSu));
        tbScreen.setVehicles("0");
        tbScreen.setVisited("0");
        tbScreen.setVehiclesPercentage("0");
        tbScreen.setVisitedPercentage("0");

        tbScreenService.updateTbScreen(tbScreen);
    }

    /**
     * 每半小时回收一次二维码
     */
    @Scheduled(cron = "0 5,35 * * * ? ")
    public void recyclingQRcodes() {

        Calendar calendar = Calendar.getInstance();
        DtoUser userDto = new DtoUser();

        Date endDateTo = DateUtils.getNowDate();
        calendar.setTime(endDateTo);
//        calendar.add(Calendar.MINUTE, -35);
//        Date endDateFrom = calendar.getTime();
//
//        userDto.setOutTimeFrom(endDateFrom);
        userDto.setOutTimeTo(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, endDateTo));
        userDto.setIsqr("1");
        List<TbVisitorUser>  userList =  tbVisitorUserService.selectTbVisitorUserList(userDto);
        if (userList != null && userList.size() > 0) {
            for (TbVisitorUser item : userList) {
                TbVisitorUser upd = new TbVisitorUser();
                upd.setId(item.getId());
                upd.setIsqr("0");
                upd.setStatus("5");
                upd.setUpdateTime(DateUtils.getNowDate());
                tbVisitorUserService.updateTbVisitorUser(upd);

                TbQr search = new TbQr();
                search.setCode(item.getQr());
                List<TbQr> qrs = tbQrService.selectTbQrList(search);
                if (qrs != null && qrs.size() > 0) {
                    for (TbQr qitem : qrs) {
                        qitem.setStatus("0");
                        qitem.setUpdateTime(DateUtils.getNowDate());
                        tbQrService.updateTbQr(qitem);
                    }
                }
            }
        }

        // 大屏信息
        TbScreen screen = new TbScreen();
        screen.setId(100L);

        LocalDateTime ldt = LocalDateTime.now();
        LocalDateTime todayZero = LocalDateTime.of(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(), 0, 0, 0);
        LocalDateTime todayLasr = LocalDateTime.of(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(), 23, 59, 59);

        Date dateFrom = Date.from(todayZero.atZone(ZoneId.systemDefault()).toInstant());
        Date dateTo = Date.from(todayLasr.atZone(ZoneId.systemDefault()).toInstant());


        DtoUser tbVisitorUser = new DtoUser();
        tbVisitorUser.setInTimeFrom(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, dateFrom));
        tbVisitorUser.setOutTimeTo(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, dateTo));

        // 预约访客数
        List<TbVisitorUser> allList = tbVisitorUserService.selectTbVisitorUserList(tbVisitorUser);
        int booking = allList.size();
        screen.setBooking(String.valueOf(booking));

        // 已到访客数
        tbVisitorUser.setInTimeTo(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getNowDate()));
        List<TbVisitorUser> visitedList = tbVisitorUserService.selectTbVisitorUserList(tbVisitorUser);
        int visited = visitedList.size();
        screen.setVisited(String.valueOf(visited));

        // 在场访客数
        tbVisitorUser.setOutTimeFrom(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getNowDate()));
        tbVisitorUser.setOutTimeTo(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, dateTo));
        tbVisitorUser.setIsqr("1");
        List<TbVisitorUser> visitoringList = tbVisitorUserService.selectTbVisitorUserList(tbVisitorUser);
        int visitoring = visitoringList.size();
        screen.setVisitoring(String.valueOf(visitoring));

        if (booking != 0 && visited != 0) {
            BigDecimal vp = new BigDecimal(visited).divide(new BigDecimal(booking), 2, BigDecimal.ROUND_HALF_UP)
                    .multiply(new BigDecimal(100));
            screen.setVisitedPercentage(vp.toString());
        }

        screen.setUpdateTime(DateUtils.getNowDate());
        tbScreenService.updateTbScreen(screen);
        WebSocketUsers.sendMessageToUsersByText("update");
    }
}
